<?php

namespace App\Services;

use App\Exceptions\TokenExpiredException;
use App\Exceptions\TokenInvalidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JwtService
{
    private string $key = "baidu1";

    public function createToken($id, $type = "user", $express_time = 2 * 24 * 60 * 60): string
    {
        $payload = [
            'iss' => 'http://www.baidu.com', //issuser
            'aud' => 'http://www.baidu.com',  //Audience
            'exp' => time()+$express_time,
            'iat' => time(),   //issued_at  = 签发时间
            'nbf' => time(),   //not_before
            'data' => [
                'id' => $id,
                'type' => $type
            ]
        ];
        return JWT::encode($payload, $this->key, 'HS256');
    }

    /**
     * @throws \Exception
     */
    public function parseToken($token)
    {
        $jwt = null;
        try {
            $jwt = JWT::decode($token, new Key($this->key, 'HS256'));
        } catch (ExpiredException $e) {
            throw new TokenExpiredException('token过期');
        } catch (\Exception $e) {
            throw new TokenInvalidException($e->getMessage());
        }
        return $jwt;
    }
}
